<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\admin\controller\Base;
use app\admin\service\ProductMerge as ProductMergeService;
use think\Request;
use think\facade\Db;

class ProductMerge extends Base
{
    protected $request;
    protected $service;
    protected $validate;
    protected $operator_id;

    public function __construct(Request $request, ProductMergeService $service)
    {
        $this->request = $request;
        $this->service = $service;
        $this->validate = new \app\admin\validate\ProductMerge();
        $this->operator_id = $request->operator_id;
    }

    public function getFieldEnum(Request $request)
    {
        $param = $request->param('field', 'ALL');
        $arrData = $this->service->getFieldEnum($param);
        return json($arrData);
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-03 14:39:09
     * @param [type] @required
     * @return Renderable
     */
    public function create()
    {
        $params = $this->request->params;
        if (!$this->validate->scene('create')->check($params)) {
            return $this->returnJsonData(100001, null, $this->validate->getError());
        }
        $params['creator'] = $this->operator_id;
        $params['create_time'] = date('Y-m-d H:i:s');
        $res = $this->service->create($params);

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";

        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-03 15:53:10
     * @param [type] @required
     * @return Renderable
     */
    public function index()
    {
        $params = empty($this->request->params) ? [] : $this->request->params;

        $pageIndex         = isset($params['pageIndex'])             ? intval($params['pageIndex'])             : 1;
        $pageSize          = isset($params['pageSize'])              ? intval($params['pageSize'])              : 1000;
        $productname       = isset($params['productname'])           ? trim($params['productname']) : null;
        $sku_product_name  = isset($params['sku_product_name'])      ? trim($params['sku_product_name']) : null;
        $algorithm         = isset($params['algorithm'])              ? intval($params['algorithm']) : null;
        $brand             = isset($params['brand'])                ? intval($params['brand']) : null;
        $currency          = isset($params['currency'])             ? intval($params['currency']) : null;




        $where[]  = ['pm.is_del', '=', 0]; // $where = [];
        $where[]  = ['pr.is_del', '=', 0];

        $query = Db::table('db_product');
        if ($productname) {
            $where[] = ['productname', 'like', "%{$productname}%"];  // invoice_no 模糊匹配
        }
        $productCondition = ['is_del' => 0];
        if ($sku_product_name) {
            $productCondition = [
                ['cname', 'like', "%{$sku_product_name}%"],
            ];
            $query->whereLike('cname', "%{$sku_product_name}%")->whereOr('abbr', "%{$sku_product_name}%");
        }
        if ($algorithm) {
            $query->whereExp('', "FIND_IN_SET({$algorithm}, algorithm)");
        }
        if ($brand) {
            $query->where('brand', $brand);
        }
        if ($currency) {
            $algorithm = Db::table('db_product_currency')->where('id', $currency)->value('algorithm');

            if ($algorithm) {
                $query->whereExp('', "FIND_IN_SET({$algorithm}, algorithm)");
            }
        }
        if ($sku_product_name || $algorithm || $brand || $currency) {
            $productIds = $query->where($productCondition)->column('id');

            $where[] = ['pr.pid', 'in', $productIds];
        }

        $field = '*';
        $res =  $this->service->getList($pageIndex, $pageSize, $where, $field);

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    public function read(Request $request)
    {
        $params = $this->request->params;
        if (!$this->validate->scene('read')->check($params)) {
            return $this->returnJsonData(100001, null, $this->validate->getError());
        }
        $res = $this->service->getInfo($params);
        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe 更新商品合并信息
     * @author: Bobo
     * @date: 2025-04-07 11:42:53
     * @param [type] @required
     * @return Renderable
     */
    public function update()
    {
        $params = $this->request->params;
        if (!$this->validate->scene('update')->check($params)) {
            return $this->returnJsonData(100001, null, $this->validate->getError());
        }

        $params['updater'] = $this->operator_id;
        $params['update_time'] = date('Y-m-d H:i:s');
        $res = $this->service->update($params);

        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-14 11:19:52
     * @param [type] @required
     * @return Renderable
     */
    public function select()
    {
        $res = $this->service->getSelectData();
        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }

    /**
     * @describe 获取已选的SKU商品（聚合商品排他用）
     * @author: Bobo
     * @date: 2025-07-09 10:14:23
     * @param [type] @required
     * @return Renderable
     */
    public function getSelectedSkuId()
    {
        $res = $this->service->getSelectedSkuId();
        $code = $res['code'];
        $data = $res['data'] ?? [];
        $message = $res['message'] ?? "";
        return $this->returnJsonData($code, $data, $message);
    }
}
